<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>预测</title>
<link rel="stylesheet" type="text/css" href="<%=path %>/style/easyui.css">
<link rel="stylesheet" type="text/css" href="<%=path %>/style/icon.css">
<link rel="stylesheet" type="text/css" href="<%=path %>/style/neweasyui/themes/gray/panel.css">
<link rel="stylesheet" type="text/css" href="<%=path %>/style/neweasyui/themes/gray/window.css">
<script type="text/javascript" src="<%=path %>/script/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="<%=path %>/script/jquery.easyui.min.js"></script>
<script type="text/javascript" src="<%=path %>/script/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="<%=path %>/script/dateFormat.js"></script>
<script type="text/javascript" src="<%=path %>/script/datagrid-bufferview.js"></script>
<script type="text/javascript" src="<%=path %>/script/common.js"></script>
<script type="text/javascript" src="<%=path %>/plugins/My97DatePicker/WdatePicker.js"></script>

<style type="text/css">
        #fm{
            margin:0;
            padding:10px 30px;
        }
        .ftitle{
            font-size:14px;
            font-weight:bold;
            padding:5px 0;
            margin-bottom:10px;
            border-bottom:1px solid #ccc;
        }
        .fitem{
            margin-bottom:17px;
        }
        .fitem label{
            display:inline-block;
            width:80px;
        }
        .fitem input{
            width:230px;
        }
</style>
</head>
<body>   
<table id="tt" title="机经预测" style="width:auto;height:800px">
	</table>
	
	<div id="toolbar" style="padding:5px;height:auto">
        <div>
         
         <!-- 搜索条件开始 -->	
        	 预测范围：
        	 	<input class="easyui-datebox" style="width:100px" id="timeRange" name="timeRange"  data-options="formatter:myformatter,parser:myparser,editable:false " />
            &nbsp;&nbsp;
		    ID：<input id="fid" type="text" class="easyui-numberbox" style="width:80px">&nbsp;&nbsp;
		            期号：<input id="fnum" type="text" class="easyui-numberbox" style="width:80px">&nbsp;&nbsp;
		            当前期:<input id="top" type="text" class="easyui-numberbox" style="width:80px">&nbsp;&nbsp;
		            状态：<select id="fstatus" class="easyui-combobox" panelHeight="auto" style="width:auto" data-options="editable:false "> 
	                <option value="" selected="selected">全部</option>
	                <option value="0">不可用</option>
	                <option value="1">可用</option>
		        </select>&nbsp;&nbsp;
		         
         <!-- 搜索条件结束 -->	
            <a href="javascript:void(0)"  class="easyui-linkbutton" iconCls="icon-search" onclick="searchData()">查询</a>&nbsp;&nbsp;
            <a href="javascript:void(0)"  class="easyui-linkbutton" iconCls="icon-add" onclick="newForecase()">添加</a>&nbsp;&nbsp;
            <a href="javascript:void(0)"  class="easyui-linkbutton" iconCls="icon-edit" onclick="editForecase()">修改</a>&nbsp;&nbsp;
        </div>
    </div>
    
    
   
    
    <!-- 添加/编辑框 开始-->
	<div id="dlg" class="easyui-dialog"
		style="width: 800px; height: 650px; padding: 10px 20px" closed="true"
		buttons="#dlg-buttons">
		<div class="ftitle">预测信息</div>
		<form id="fm" method="post"  validate enctype="multipart/form-data">
							<fieldset style="width:400px;">
								<legend>课程添加:</legend>
								<div class="fitem">
								</div>
								<div class="fitem">
									<label>机经名称:</label>  
								    <input  class="easyui-textbox" name="name" id="name" required style="width:160px;"   />
								</div>
								<div class="fitem">
									<label>描述:</label>  
								    <input  class="easyui-textbox" name="desc" id="desc"  style="width:160px;"   />
								</div>
								<div class="fitem" >
									<label>是否推荐:</label>  
								    <select class="easyui-combobox" name="recommended" id="recommended" required panelHeight="auto">
								      	<option value="0">不推荐</option>
								      	<option value="1">推荐</option>
								     </select>
								</div>
								<div class="fitem" >
									<label>出现频率:</label>  
								    <input  class="easyui-textbox" name="frequency" id="frequency"  style="width:160px;"   />
								</div>
								<div class="fitem" >
									<label>图片:</label>  
								    <input  type="file" name="file" id="file"  style="width:160px;"   />
								</div>
								<div class="fitem" >
									<label>排序号:</label>  
								    <input  class="easyui-textbox" name="seqNum" id="seqNum" required  style="width:160px;"   />
								</div>
								<div class="fitem" >
									<label>课程类型:</label>  
								    <input  class="easyui-textbox" name="type" id="type"  style="width:160px;"  />
								    <font color="red">*|&nbsp;&nbsp;机经设为 1 ,其他设为 0 </font>
								</div>
							</fieldset>
								
				<div class="fitem">
				</div>
			    <input type="hidden" name="fid" id="fid" />
				<div class="fitem">
					<label>期号:</label>  
				    第<input  class="easyui-textbox" name="forecastNum" id="forecastNum" required style="width:80px;"   />期
				    <span id="errtip"></span>  
		            <input type="checkbox" name="status" id="statuschk" value="1"   style="width:23px;">可用
				</div>
				
				<div class="fitem">
					<label>日期:</label> 
					预测范围<input class="easyui-datebox" style="width:100px" required id="timeRange2" name="timeRange"  data-options="formatter:myformatter,parser:myparser,editable:false " />
					<!-- 
					<input class="easyui-datebox" style="width:100px" name="fTime3"  data-options="formatter:myformatter,parser:myparser,editable:false " />
					 -->
				</div>
				
				<div class="fitem" style="border:dotted 1px;width: 563px;">
					<div style="margin-top:10px;">
					     <div style="float: left;width: 80px;">选题:</div> 
					     <div  style="float: left;">
					       <a href="javascript:void(0)"  class="easyui-linkbutton" iconCls="icon-add" onclick="selQuestion('questionDiv','')">新增</a>
					     </div> 
					</div>
					<br/><br/>
					<div id="questionDiv">
					    
					</div>
				</div>
				
				<!-- 选题情况总结 -->
				<div class="fitem" id="sammarDiv" style="border:dotted 1px;width: 563px;display:none;">
					<div style="margin-top: 19px;margin-left: 82px;margin-bottom: 10px;" id="sammar">
					     
					</div>
				</div>
				<!-- 选题情况总结结束 -->
			
		</form>
	</div>
	<div id="dlg-buttons">
		<a href="javascript:void(0)" class="easyui-linkbutton c6"
			iconCls="icon-ok" onclick="saveOrUpdateQBank()" style="width: 90px">Save</a> <a
			href="javascript:void(0)" class="easyui-linkbutton"
			iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')"
			style="width: 90px">Cancel</a>
	</div>
	 <!-- 添加/编辑框结束-->
	 
</body>
<script type="text/javascript">
$.ajaxSetup({cache:false,async:false});
$(function(){
	$('#tt').datagrid({
		url:'<%=basePath %>test/forecast/list',
		method:'get',
		singleSelect:true,toolbar:'#toolbar',remoteSort:false,pageSize:50,nowrap:false,
		//pagination:true,fitColumns:true,
		rownumbers:true,
	    columns:[[
	        {field:'id',title:'ID',sortable:true,width:50,hidden:true},
	        {field:'name',title:'机经',width:80},
	        {field:'desc',title:'描述',width:80},
	        {field:'recommended',title:'是否推荐',width:80},
	        {field:'frequency',title:'出现频率',width:80,
	            formatter: function(value,row,index){
	                var str="" ;
	                return value+"%";
	              }
	            },
	        {field:'imgUrl',title:'图片',width:550},
	        {field:'seqNum',title:'排序号',width:80},
	        {field:'type',title:'课程类型',width:80},
	        
	        {field:'clsClassId',title:'课程ID',width:80,hidden:true},
	        {field:'forecastNum',title:'期号',sortable:true,width:80},
	        {field:'timeRange1',title:'预测范围',sortable:true,width:200,formatter:Common.DateFormatter2 },
	        /**
	        {field:'forecastTime3',title:'预测范围3',sortable:true,width:200,formatter:Common.DateFormatter },
	        */
	        {field:'status',title:'状态',sortable:true,width:100,
	        	formatter:function(value){
	        		if(value==0){
	        			return "不可用" ;
	        		}else{
	        			return "可用" ;
	        		}
	        	}
	        }  
	    ]]
	});
});

	function searchData(){
		
		var timeRange = $("input[name='timeRange']:first").val();
		var top = $("#top").val();
		var id = $("#fid").textbox('getValue') ;
		var fnum = $("#fnum").textbox('getValue');
	    var status = $("#fstatus").combobox('getValue') ;
		$('#tt').datagrid({
			url:'<%=basePath %>test/forecast/list?fid='+id+'&forecastNum='+fnum+'&timeRange='+timeRange+'&top='+top+'&status='+status,
			method:'get'
		});
	}
	
	//-------------------------------------------------
	var qindex = 0 ,onestarcount=0,twostarcount=0,thirdstarcount=0,fourstarcount=0,fivestarcount=0 ;
	//选择题库
	function selQuestion(divId,qnum){
	   qindex++ ;
	   var _div = $('<div style="margin-top: 19px;margin-left: 82px;margin-bottom: 10px;">'+
				  '      <span name="qindex">'+qindex+'</span>. '+
				  '      <span>'+
				      '    题号:<input type="text" name="qnum" style="width:86px;" value="'+qnum+'" onblur="checkQnumIsExist(this.value,this)" onkeyup="checkQnumIsExist(this.value,this)" /> - '+
				    '    &nbsp;<a href="#" onclick="delQ(this)">删除</a>'+
				    '</div>');
	       $("#"+divId).prepend(_div) ;
	      
	       $(_div).find("select option").each(function(){
	    	   if(qstar==$(this).attr('value')){
	    		   $(this).attr('selected','selected') ;
	    	   }
	       });
	     //  var currstar = $(_div).find("select").val() ;
	     //  dealstar(currstar,true) ;
	}
	//处理指数
	function dealstar(star,isIncrement){
		if(star==1){
	       onestarcount = isIncrement?++onestarcount:--onestarcount ;
	    }else if(star==2){
	    	twostarcount = isIncrement?++twostarcount:--twostarcount ;
	    }else if(star==3){
	    	thirdstarcount = isIncrement?++thirdstarcount:--thirdstarcount;
	    }else if(star==4){
	    	fourstarcount = isIncrement?++fourstarcount:--fourstarcount;
	    }else if(star==5){
	    	fivestarcount = isIncrement?++fivestarcount:--fivestarcount;
	    }
		showstar();
	}
	//显示指数
	function showstar(){
		if(onestarcount+twostarcount+thirdstarcount+fourstarcount+fivestarcount>0){
			$("#sammar").empty();
			
			var _p = "<p>选题情况如下：</p>" ;
			var _p1 = "<p style='margin-left: 43px;'>重要指数为1的选题共有"+onestarcount+"道</p>" ;
			var _p2 = "<p style='margin-left: 43px;'>重要指数为2的选题共有"+twostarcount+"道</p>" ;
			var _p3 = "<p style='margin-left: 43px;'>重要指数为3的选题共有"+thirdstarcount+"道</p>" ;
			var _p4 = "<p style='margin-left: 43px;'>重要指数为4的选题共有"+fourstarcount+"道</p>" ;
			var _p5 = "<p style='margin-left: 43px;'>重要指数为5的选题共有"+fivestarcount+"道</p>" ;
			 
			$("#sammar").append(_p).append(_p1).append(_p2).append(_p3).append(_p4).append(_p5) ;
			$("#sammarDiv").css('display','block');
		}else{
			$("#sammarDiv").css('display','none');
		}
	}
	
	//删除题
//删除题
	function delQ(obj){
		
		//当前删除的题的索引
		//var currqindex = parseInt($(obj).parent().find("span[name='qindex']").html()) ;
		//var qstar =  parseInt($(obj).parent().find("select").val()) ;
		//此索引之后的索引依次减1
		$(obj).parent().parent().remove();
		var items = $("span[name='qindex']");
		var size =items.length;
		qindex = size ;
		$(items).each(function(){
			$(this).html(size);
			size--;
		});
		
		 
		//统计更新
		//dealstar(qstar,false) ;
	}
	 
		
	var url = '' ;
	
	//添加预测
	function newForecase(){
		 qindex=0;
		
		 $("#questionDiv").empty();
		 $('#dlg').dialog('open').dialog('setTitle','添加题库');
		 $('#fm').form('clear');
		 $("#statuschk").attr('checked','on') ;
		 url = '<%=basePath%>test/forecast/save';
	}
	
	//编辑题库
	function editForecase(){
		 qindex = 0;
		 var row = $('#tt').datagrid('getSelected');
		 if (row){
			 row.fid=row.id;
			 $("#questionDiv").empty();
			 if(row.timeRange1){
				 row.timeRange = Common.DateFormatter2(row.timeRange1);
			 }
			 
		$('#questionDiv').empty();
		 $('#dlg').dialog('open').dialog('setTitle','编辑题库');
		 $.ajax({
            type: "get",//使用get方法访问后台
            dataType: "json",//返回json格式的数据
            url: "<%=basePath%>test/fctquestion/list?fid="+row.id,//要访问的后台地址
             beforeSend: function () {
                   $.messager.progress({
	                title:'请稍等',
	                msg:'正在获取...',
	                text:'拼命获取中',
	                interval:500
	            });                
           },
            complete :function(){
            	$.messager.progress('close');
            },//AJAX请求完成时隐藏loading提示
            success: function(msg){//msg为返回的数据，在这里做数据绑定
                var data = msg.content;
                $.each(data, function(i, n){
                     selQuestion('questionDiv',n.questionNum) ;
                });
		
			 }
			  });
			 $('#fm').form('load',row);
			 url = '<%=basePath%>test/forecast/update?fid='+row.id;
		 }
	}
	var flag = true;
	//添加或修改题库
	function saveOrUpdateQBank(){
	   if(!isEqual()){
		   $.messager.alert("提示","机经名称中前缀中的时间必须与预测范围的时间相等");
		  return ; 
	   }
	   if(isExist()){
		   $.messager.alert("提示","机经已存在,请重新填写");
		  return ; 
	   }
	   $('#fm').form('submit', {
			url : url,
			onSubmit : function() {
				return $(this).form('validate');
				$.messager.progress({
	                title:'请稍等',
	                msg:'正在更新...',
	                text:'拼命更新中',
	                interval:500
	            });
	            if(!checkQnumIsError() && $(this).form('validate') && flag){
	            	$.messager.progress('close');
	            }
				return checkQnumIsError() && $(this).form('validate') && flag;
			},
			success : function(result) {
				 $.messager.progress('close');
				if (result==0) {
					$.messager.show({
						title : 'Error',
						msg : '服务器出错，请稍后再试'
					});
				} else {
					$('#dlg').dialog('close'); // close the dialog
					$('#tt').datagrid('reload'); // reload the user data
				}
			}
		});
	}
	
	//使用题号检查题是否存在
	function checkQnumIsExist(qnum,obj){
		 
		if(qnum.length>0){
			$.ajax({
				type: 'get'  ,
				url : '<%=basePath%>test/experience/checkQnumIsExist' ,
				data: 'qnum='+qnum ,
				success:function(rs){
					if(rs==1){
						$(obj).removeClass('validatebox-invalid') ;
					}else{
						$(obj).addClass('validatebox-invalid') ;
					}
				}
			});
		}
	}
	//检查题号输入是否有误
	function checkQnumIsError(){
		$("#questionDiv").find("input[name='qnum']").each(function(){
			if($(this).val().length==0){
				$(this).addClass('validatebox-invalid') ;
			}
			if($(this).hasClass('validatebox-invalid')){
				return false ;
			}
		});
		return true;
	}
	//检查期号是否存在
	function checkFnumIsExist(fnum,obj){
		if(fnum.length>0){
			$.ajax({
				type: 'get'  ,
				url : '<%=basePath%>/test/forecast/hasForecastNum',
				data: 'forecastNum='+fnum,
				success:function(rs){
					if(rs && rs>0){
						//期号已存在
						$("#errtip").html("<font color='red'>该期号已存在</font>");
						flag = false ;
					}else{
						$("#errtip").html("");
						flag = true ;
					}
				}
			});
		}
	}

	function hasForecastNum(forecastNum,obj){
		if(qnum.length>0){
			$.ajax({
				type: 'get',
				url : '<%=basePath%>/test/forecast/hasForecastNum',
				data: 'forecastNum='+forecastNum,
				success:function(rs){
					if(rs==0){
						$(obj).removeClass('validatebox-invalid') ;
					}else{
						$(obj).addClass('validatebox-invalid') ;
					}
				}
			});
		}
		
	}
	
	$(function(){
		$("#forecastNum").parent().find("span .textbox-text").keyup(function(){
		    checkFnumIsExist($(this).val(),this) ;
		});
	});
	//判断机经中 机经名字中的时间和 预测时间是否一致
	function isEqual(){
		var timeRange = $("input[name='timeRange']:last").val();
		var name = $("#name").val();
		var preName = name.split(" ");
		if(timeRange != preName[0]){
			return false;
		}
		return true;
	}
	//判断要保存的机经是否已经存在
	function isExist(){
		var b = false;
		var timeRange = $("input[name='timeRange']:last").val();
		var fid =  $("input[name='fid']").val();
		$.post("<%=basePath %>service/class/sys/judgeExist",{'fid':fid,'timeRange':timeRange},function(data){
			//0 已存在
			if(data.status == "-1"){
				b= true;
			}
		});
		return b;
	}
</script>
</html>